﻿using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using PMIS.Shared.DTO;
using PMIS.Shared.Models;
using PMIS.WebApi.Model;
using PMIS.WebApi.Services;
using PMIS.WebApi.SnowflakeId;
using PMIS.WebApi.Common.Attributes;

namespace PMIS.WebApi.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class MenuController : ControllerBase
    {
        private readonly IMapper _mapper;
        private readonly IMenuService _service;
        private readonly SnowflakeIdGenerator _idGenerator;

        public MenuController(IMenuService service, IMapper mapper, SnowflakeIdGenerator idGenerator)
        {
            _service = service;
            _mapper = mapper;
            _idGenerator = idGenerator;
        }

        [HttpPost]
        public async Task<IActionResult> Add(MenuDto m)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            var menu = _mapper.Map<Menu>(m);
            menu.Id = _idGenerator.GetId(); 
            var data = await _service.AddEntityAsync(menu);
            var res = new ApiResult() { data = data };
            return Ok(res);
        }

        [HttpPost]
        public async Task<IActionResult> Delete(List<string> ids)
        {
            var data = await _service.DeleteEntityAsync<Menu>(x => ids.Contains(x.Id));
            var res = new ApiResult() { data = data };
            return Ok(res);
        }

        [HttpGet]
        public async Task<IActionResult> Get(string id)
        {
            var data = await _service.GetEntityAsync(id);
            var res = new ApiResult() { data = data };
            return Ok(res);
        }

        [HttpPut]
        public async Task<IActionResult> Update(MenuDto m)
        {
            var menu = _mapper.Map<Menu>(m);
            var data = await _service.UpdateEntityAsync(menu);
            var res = new ApiResult() { data = data };
            return Ok(res);
        }

        [HttpGet]
        public async Task<IActionResult> GetList(int? pageNum, int? pageSize)
        {
            var data = await _service.GetEntityListAsync(pageNum, pageSize);
            var res = new ApiResult() { data = data };
            return Ok(res);
        }
    }
}
